﻿using System;
using System.Collections.Generic;
using System.Linq;
using PagedList;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using EventPlanner.Models;
using System.Net.Mail;

using System.Net;

namespace EventPlanner.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    if (Membership.GetUser(model.UserName) != null && !Membership.GetUser(model.UserName).IsApproved)
                        ModelState.AddModelError("", "Su cuenta ha sido desactivada. Por favor póngase en contacto con un administrador");
                    else
                        ModelState.AddModelError("", "Nombre de Usuario o Contraseña incorrectos.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            ViewBag.roles = ListaDeRoles();
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model, string role)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(model.UserName, role);
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }
            ViewBag.roles = ListaDeRoles();
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }


        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ResetPassword(string Name)
        {
            MembershipUser currentUser = Membership.GetUser(Name);
            string password = currentUser.ResetPassword();
            ViewData["pass"] = password;

            try
            {
                SendEmail(currentUser.Email, "Nueva contraseña temporal", "Su nueva contraseña es: " + password);
            }
            catch
            {
                return RedirectToAction("CustomError", "Error", new { MensajeError = "Error al procesar el envio de mail" });
            }
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }
                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "La contraseña actual es incorrecta o la nueva inválida.");
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        // GET: /Evento/Details/5

        [Authorize(Roles = "Administrator, Guest, Publisher")]
        public ActionResult Details()
        {
            MembershipUser Usuario = Membership.GetUser(User.Identity.Name);
            UserViewModel usuariosmodel = new UserViewModel()
            {
                UserName = Usuario.UserName,
                Email = Usuario.Email,
                LastSeen = Usuario.LastActivityDate,
                Created = Usuario.CreationDate,
                 Role = EventPlanner.Authorization.util.GetUserRole(User.Identity.Name)
                
            };
            return View(usuariosmodel);
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult DetailsAdmin(string Name)
        {
            MembershipUser Usuario = Membership.GetUser(Name);

            UserViewModel usuariosmodel = new UserViewModel()
            {
                UserName = Usuario.UserName,
                Email = Usuario.Email,
                LastSeen = Usuario.LastActivityDate,
                Created = Usuario.CreationDate,
                Role = EventPlanner.Authorization.util.GetUserRole(Name)

            };
            return View(usuariosmodel);
        }

        // GET: /Evento/Delete/5
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(string Name)
        {
            if (Name == User.Identity.Name)
            {
                return RedirectToAction("CustomError", "Error", new { MensajeError = "No puede eliminarse a si mismo" });
            }
            else
            {
                MembershipUser Usuario = Membership.GetUser(Name);

                if (Usuario == null)
                    return RedirectToAction("CustomError", "Error", new { MensajeError = "El usuario ya no existe." });
                else
                {
                    UserViewModel usuariosmodel = new UserViewModel()
                  {
                      UserName = Usuario.UserName,
                      Email = Usuario.Email,
                      LastSeen = Usuario.LastActivityDate,
                      Created = Usuario.CreationDate
                  };
                    return View(usuariosmodel);
                }
            }
        }

        // POST: /Account/Delete/

        [HttpPost, ActionName("Delete")]
        [Authorize(Roles = "Administrator")]
        public ActionResult DeleteConfirmed(string name)
        {
            Membership.DeleteUser(name);
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Administrator, Guest, Publisher")]
        public ActionResult Deactivate(string Name)
        {

            MembershipUser u = Membership.GetUser(Name);
            if (Name == User.Identity.Name && EventPlanner.Authorization.util.GetUserRole(User.Identity.Name) == "Administrator")
                return RedirectToAction("CustomError", "Error", new { MensajeError = "Por razones de seguridad un administrador no puede desactivar su propia cuenta" });
            else
            {
                u.IsApproved = false;
                Membership.UpdateUser(u);
                if (EventPlanner.Authorization.util.GetUserRole(User.Identity.Name) != "Administrator") LogOff();
                return RedirectToAction("Index");
            }
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Activate(string Name)
        {
            MembershipUser u = Membership.GetUser(Name);
            u.IsApproved = true;
            Membership.UpdateUser(u);
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.UserNameSortParm = String.IsNullOrEmpty(sortOrder) ? "UserName desc" : "";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "Email desc" : "Email";
            ViewBag.RoleSortParm = sortOrder == "Role" ? "Role desc" : "Role";

            if (Request.HttpMethod == "GET")
            {
                searchString = currentFilter;
            }
            ViewBag.CurrentFilter = searchString;

            var model = Membership
                .GetAllUsers()
                .Cast<MembershipUser>()
                .Select(x => new UserViewModel
                {
                    UserName = x.UserName,
                    Email = x.Email,
                    Role = EventPlanner.Authorization.util.GetUserRole(x.UserName)
                    
                });

            if (!String.IsNullOrEmpty(searchString))
            {
                model = from s in model
                        where (s.UserName.ToUpper().Contains(searchString.ToUpper())
                                     || s.Email.ToUpper().Contains(searchString.ToUpper())
                                      || s.Role.ToUpper().Contains(searchString.ToUpper()))
                        select s;
            }

            ViewBag.UserNameAddOn = ViewBag.EmailAddOn = ViewBag.RoleAddOn = "";
            switch (sortOrder)
            {
                case "UserName desc":
                    model = model.OrderByDescending(s => s.UserName);
                    ViewBag.NameAddOn = "\u2193";
                    break;
                case "Email":
                    model = model.OrderBy(s => s.Email);
                    ViewBag.DateAddOn = "\u2191";
                    break;
                case "Email desc":
                    model = model.OrderByDescending(s => s.Email);
                    ViewBag.DateAddOn = "\u2193";
                    break;
                case "Role":
                    model = model.OrderBy(s => s.Role);
                    ViewBag.OrgAddOn = "\u2191";
                    break;
                case "Role desc":
                    model = model.OrderByDescending(s => s.Role);
                    ViewBag.OrgAddOn = "\u2193";
                    break;
                default:
                    model = model.OrderBy(s => s.UserName);
                    ViewBag.NameAddOn = "\u2191";
                    break;
            }
            int pageSize = 10;
            int pageNumber = (page ?? 1);

            return View(model.AsQueryable().ToPagedList(pageNumber, pageSize));
            //return View(model);
        }


        private List<SelectListItem> ListaDeRoles()
        {
            List<SelectListItem> lista = new List<SelectListItem>();
            SelectListItem s1 = new SelectListItem();
            s1.Value = "Publisher";
            s1.Text = "Publicador";
            lista.Add(s1);
            SelectListItem s2 = new SelectListItem();
            s2.Value = "Administrator";
            s2.Text = "Administrador";
            lista.Add(s2);
            SelectListItem s3 = new SelectListItem();
            s3.Value = "Guest";
            s3.Text = "Asistente";
            lista.Add(s3);
            return lista;
        }

        public void SendEmail(string address, string subject, string message)
        {
            string email = "comision5@gmail.com";
            string password = "event-planner-password";

            var loginInfo = new NetworkCredential(email, password);
            var msg = new MailMessage();
            var smtpClient = new SmtpClient("smtp.gmail.com", 587);

            msg.From = new MailAddress(email);
            msg.To.Add(new MailAddress(address));
            msg.Subject = subject;
            msg.Body = message;
            msg.IsBodyHtml = true;

            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = loginInfo;

            /*descomentar para habilitar el envio de email
            smtpClient.Send(msg);
             * */
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
